//###############
//FILE : FileWantServersSession.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############

package oop.ex3.protocol.sessions;

import oop.ex3.protocol.messages.WantServersMsg;
import oop.ex3.protocol.messages.ContainNameServerMsg;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import oop.ex3.communication.SocketAddress;
import oop.ex3.exceptions.InvalidMessageException;

/**
 * Ask a NS for the list of NSs it knows about.
 * @author daniel
 */

public class FileWantServersSession extends FileToNameSession {
    private ArrayList<SocketAddress> _nameServersOutput;

    public FileWantServersSession() {
        super();
        _nameServersOutput = new ArrayList<SocketAddress>();
    }

    /**
     * Get the list of NSs that we asked for.
     * @return The NS list.
     */
    public ArrayList<SocketAddress> getNameServers() {
        return _nameServersOutput;
    }

    @Override
    protected boolean specExecuteSession(DataInputStream inputStream, DataOutputStream outputStream) throws IOException, InvalidMessageException {
        
        if (!initSession(inputStream, outputStream))
            return false;
        
        WantServersMsg wantServers = new WantServersMsg();
        wantServers.send(outputStream);

        //receive the list of nameservers
        while (!_endList.matchHeader(inputStream)) {
            ContainNameServerMsg containServer = new ContainNameServerMsg();
            containServer.receive(inputStream);
            String ip = containServer.getIp();
            int port = containServer.getPort();
            _nameServersOutput.add(new SocketAddress(ip, port));
        }

        _endList.receive(inputStream);

        if (!endSession(inputStream, outputStream))
            return false;

        return true;
    }




}
